import BasePlugin from './BasePlugin';

/**
 * 滤镜插件 - 处理图像滤镜
 */
export default class FilterPlugin extends BasePlugin {
    constructor() {
        super();
        this.filters = new Map();
        this._initializeFilters();
    }

    /**
     * 初始化插件
     */
    init(editor) {
        super.init(editor);
        this._setupEventListeners();
    }

    /**
     * 初始化滤镜
     */
    _initializeFilters() {
        // 灰度
        this.filters.set('grayscale', {
            name: 'Grayscale',
            create: () => new fabric.Image.filters.Grayscale()
        });

        // 反色
        this.filters.set('invert', {
            name: 'Invert',
            create: () => new fabric.Image.filters.Invert()
        });

        // 棕褐色
        this.filters.set('sepia', {
            name: 'Sepia',
            create: () => new fabric.Image.filters.Sepia()
        });

        // 黑白
        this.filters.set('blackwhite', {
            name: 'Black/White',
            create: () => new fabric.Image.filters.BlackWhite()
        });

        // 亮度
        this.filters.set('brightness', {
            name: 'Brightness',
            create: (value = 0) => new fabric.Image.filters.Brightness({
                brightness: value
            })
        });

        // 对比度
        this.filters.set('contrast', {
            name: 'Contrast',
            create: (value = 0) => new fabric.Image.filters.Contrast({
                contrast: value
            })
        });

        // 饱和度
        this.filters.set('saturation', {
            name: 'Saturation',
            create: (value = 0) => new fabric.Image.filters.Saturation({
                saturation: value
            })
        });

        // 色相
        this.filters.set('hue', {
            name: 'Hue',
            create: (value = 0) => new fabric.Image.filters.HueRotation({
                rotation: value
            })
        });

        // 噪点
        this.filters.set('noise', {
            name: 'Noise',
            create: (value = 0) => new fabric.Image.filters.Noise({
                noise: value
            })
        });

        // 模糊
        this.filters.set('blur', {
            name: 'Blur',
            create: (value = 0) => new fabric.Image.filters.Blur({
                blur: value
            })
        });

        // 锐化
        this.filters.set('sharpen', {
            name: 'Sharpen',
            create: () => new fabric.Image.filters.Convolute({
                matrix: [0, -1, 0, -1, 5, -1, 0, -1, 0]
            })
        });

        // 浮雕
        this.filters.set('emboss', {
            name: 'Emboss',
            create: () => new fabric.Image.filters.Convolute({
                matrix: [1, 1, 1, 1, 0.7, -1, -1, -1, -1]
            })
        });
    }

    /**
     * 获取所有滤镜
     */
    getFilters() {
        return Array.from(this.filters.entries()).map(([id, filter]) => ({
            id,
            name: filter.name
        }));
    }

    /**
     * 应用滤镜
     */
    applyFilter(imageObject, filterId, value) {
        if (!this.isEnabled() || !this.canvas || !imageObject) return;

        const filter = this.filters.get(filterId);
        if (!filter) return;

        // 获取当前滤镜索引
        const filterIndex = this._getFilterIndex(imageObject, filterId);
        const newFilter = filter.create(value);

        if (filterIndex >= 0) {
            // 更新现有滤镜
            imageObject.filters[filterIndex] = newFilter;
        } else {
            // 添加新滤镜
            imageObject.filters.push(newFilter);
        }

        // 应用滤镜
        imageObject.applyFilters();
        this.canvas.renderAll();

        this._emitFilterEvent('apply', imageObject, filterId, value);
    }

    /**
     * 移除滤镜
     */
    removeFilter(imageObject, filterId) {
        if (!this.isEnabled() || !this.canvas || !imageObject) return;

        const filterIndex = this._getFilterIndex(imageObject, filterId);
        if (filterIndex >= 0) {
            imageObject.filters.splice(filterIndex, 1);
            imageObject.applyFilters();
            this.canvas.renderAll();

            this._emitFilterEvent('remove', imageObject, filterId);
        }
    }

    /**
     * 清除所有滤镜
     */
    clearFilters(imageObject) {
        if (!this.isEnabled() || !this.canvas || !imageObject) return;

        imageObject.filters = [];
        imageObject.applyFilters();
        this.canvas.renderAll();

        this._emitFilterEvent('clear', imageObject);
    }

    /**
     * 获取滤镜值
     */
    getFilterValue(imageObject, filterId) {
        if (!imageObject) return null;

        const filterIndex = this._getFilterIndex(imageObject, filterId);
        if (filterIndex >= 0) {
            const filter = imageObject.filters[filterIndex];
            switch (filterId) {
                case 'brightness':
                    return filter.brightness;
                case 'contrast':
                    return filter.contrast;
                case 'saturation':
                    return filter.saturation;
                case 'hue':
                    return filter.rotation;
                case 'noise':
                    return filter.noise;
                case 'blur':
                    return filter.blur;
                default:
                    return null;
            }
        }
        return null;
    }

    /**
     * 获取滤镜索引
     */
    _getFilterIndex(imageObject, filterId) {
        if (!imageObject || !imageObject.filters) return -1;

        const filter = this.filters.get(filterId);
        if (!filter) return -1;

        return imageObject.filters.findIndex(f => {
            return f instanceof fabric.Image.filters[filter.create().type];
        });
    }

    /**
     * 发送滤镜事件
     */
    _emitFilterEvent(type, imageObject, filterId, value) {
        this.editor.emit('filter:applied', {
            type,
            target: imageObject,
            filterId,
            value
        });
    }

    /**
     * 设置事件监听
     */
    _setupEventListeners() {
        if (!this.canvas) return;

        // 监听对象选择事件
        this.canvas.on('selection:created', (e) => {
            if (!this.isEnabled()) return;

            const activeObject = e.target;
            if (activeObject instanceof fabric.Image) {
                this.editor.emit('filter:selectable', true);
            }
        });

        this.canvas.on('selection:updated', (e) => {
            if (!this.isEnabled()) return;

            const activeObject = e.target;
            if (activeObject instanceof fabric.Image) {
                this.editor.emit('filter:selectable', true);
            } else {
                this.editor.emit('filter:selectable', false);
            }
        });

        this.canvas.on('selection:cleared', () => {
            if (!this.isEnabled()) return;
            this.editor.emit('filter:selectable', false);
        });
    }

    /**
     * 销毁插件
     */
    destroy() {
        if (this.canvas) {
            // 清除所有对象的滤镜
            this.canvas.getObjects('image').forEach(obj => {
                this.clearFilters(obj);
            });
        }
        super.destroy();
    }
} 